const fetch = require('node-fetch');
const CryptoJS = require('crypto-js');

async function testAPI() {
  const baseURL = 'http://localhost:3001';
  
  console.log('=== 测试健康检查 ===');
  try {
    const response = await fetch(`${baseURL}/api/health`);
    const data = await response.json();
    console.log('健康检查:', response.status, data);
  } catch (error) {
    console.error('健康检查失败:', error.message);
  }

  console.log('\n=== 测试登录（原始密码）===');
  let token = null;
  try {
    const response = await fetch(`${baseURL}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: 'admin', password: 'admin123' })
    });
    const data = await response.json();
    console.log('登录（原始密码）:', response.status, data);
  } catch (error) {
    console.error('登录失败:', error.message);
  }

  console.log('\n=== 测试登录（MD5密码）===');
  try {
    const hashedPassword = CryptoJS.MD5('admin123').toString();
    console.log('MD5密码:', hashedPassword);
    const response = await fetch(`${baseURL}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: 'admin', password: hashedPassword })
    });
    const data = await response.json();
    console.log('登录（MD5密码）:', response.status, data);
    token = data.data?.token;
  } catch (error) {
    console.error('登录失败:', error.message);
  }

  if (!token) {
    console.log('❌ 无法获取token，停止后续测试');
    return;
  }

  console.log('\n=== 测试资产接口 ===');
  try {
    const response = await fetch(`${baseURL}/api/assets`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    const data = await response.json();
    console.log('资产列表:', response.status, data);
  } catch (error) {
    console.error('资产接口失败:', error.message);
  }

  console.log('\n=== 测试用户接口 ===');
  try {
    const response = await fetch(`${baseURL}/api/users`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    const data = await response.json();
    console.log('用户列表:', response.status, data);
  } catch (error) {
    console.error('用户接口失败:', error.message);
  }

  console.log('\n=== 测试盘点接口 ===');
  try {
    const response = await fetch(`${baseURL}/api/inventory`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    const data = await response.json();
    console.log('盘点列表:', response.status, data);
  } catch (error) {
    console.error('盘点接口失败:', error.message);
  }
}

testAPI().catch(console.error);
